package com.nb.nbbase2.listener;

import com.nb.nbbase2.entity.Order;
import com.nb.nbbase2.enums.OrderStatus;
import com.nb.nbbase2.enums.OrderStatusChangeEvent;
import com.nb.nbbase2.mapper.OrderMapper;
import com.nb.nbbase2.utils.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * author：芋道源码
 */
@Component("orderStateListener")
@WithStateMachine(name = "orderStateMachine")
@Slf4j
public class OrderStateListener {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StateMachine<OrderStatus, OrderStatusChangeEvent> orderStateMachine;


    /**
     * 从待支付 ---> 已支付待发货
     * @param message
     */
    @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
    @Transactional(rollbackFor = Exception.class)
    public void payTransition(Message<OrderStatusChangeEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("支付，状态机反馈信息：{}", message.getHeaders().toString());

        try {
            //更新订单
            order.setStatus(OrderStatus.WAIT_DELIVER.getKey());
            orderMapper.updateById(order);
            //TODO 其他业务
            log.info("从待支付 ---> 已支付待发货，执行其他业务");
            //模拟异常
            if(StringUtils.equals(order.getOrderCode(),"666666")){
                throw new RuntimeException("执行业务异常");
            }
            //成功 则为1
            orderStateMachine.getExtendedState().getVariables().put(SysConstant.payTransition+order.getId(),1);
        } catch (Exception e) {
            //如果出现异常，则进行回滚
            log.error("payTransition 出现异常：{}",e);
            //将异常信息变量信息中，失败则为0
            orderStateMachine.getExtendedState().getVariables().put(SysConstant.payTransition+order.getId(), 0);
            throw e;

        }

    }

    /**
     * 从待发货---->已发货待收货
     * @param message
     */
    @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
    @Transactional(rollbackFor = Exception.class)
    public void deliverTransition(Message<OrderStatusChangeEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("发货，状态机反馈信息：{}", message.getHeaders().toString());

        try {
//更新订单
            order.setStatus(OrderStatus.WAIT_RECEIVE.getKey());
            orderMapper.updateById(order);
            //TODO 其他业务
            log.info("从待发货---->已发货待收货，执行其他业务");
            //模拟异常
            if(StringUtils.equals(order.getOrderCode(),"666666")){
                throw new RuntimeException("执行业务异常");
            }
            //成功 则为1
            orderStateMachine.getExtendedState().getVariables().put(SysConstant.deliverTransition+order.getId(),1);
        }catch (Exception e){
//如果出现异常，则进行回滚
            log.error("payTransition 出现异常：{}",e);
            //将异常信息变量信息中，失败则为0
            orderStateMachine.getExtendedState().getVariables().put(SysConstant.deliverTransition+order.getId(), 0);
            throw e;
        }

    }

    /**
     * 从待收货 ----> 已完成
     * @param message
     */
    @OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
    @Transactional(rollbackFor = Exception.class)
    public void receiveTransition(Message<OrderStatusChangeEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("确认收货，状态机反馈信息：{}", message.getHeaders().toString());


        try {
            //更新订单
            order.setStatus(OrderStatus.FINISH.getKey());
            orderMapper.updateById(order);
            //TODO 其他业务
            log.info("从待收货 ----> 已完成，执行其他业务");
            //模拟异常
            if(StringUtils.equals(order.getOrderCode(),"666666")){
                throw new RuntimeException("执行业务异常");
            }
            //成功 则为1
            orderStateMachine.getExtendedState().getVariables().put(SysConstant.receiveTransition+order.getId(),1);
        }catch (Exception e){
//如果出现异常，则进行回滚
            log.error("payTransition 出现异常：{}",e);
            //将异常信息变量信息中，失败则为0
            orderStateMachine.getExtendedState().getVariables().put(SysConstant.receiveTransition+order.getId(), 0);
            throw e;
        }
    }
}